import {Button, Col, Form, Input, message, Modal, Popconfirm, Row, Table} from "antd";
import React, {useEffect, useState, useTransition} from "react";
import './index.scss'
import {ColumnsType} from "antd/es/table";
import {JurisdictionType, MetaType, ModalType, UserBodyType} from "../../util/publicType";
import {createUser, delUser, editUser, jurisdictionList, userList} from "../../api";
import {AxiosResponse} from "axios";
import Checkbox from "antd/lib/checkbox";
import RequestLoading from "../../components/RequestLoading";

interface DataType {
    id: string,
    username: string,
    created_at: number,
    jurisdictions: Array<{
        id: string,
        name: string,
    }>
}

const User = () => {
    const [loading, setTransition] = useTransition();
    // 搜索表单
    const [searchForm] = Form.useForm();
    // 用户表单
    const [userForm] = Form.useForm();

    // 名字搜索参数
    const [username, setUsername] = useState<string | null>(null);

    // 数据源
    const [data, setData] = useState<DataType[]>([]);

    // 分页
    const [page, setPage] = useState<number>(1);
    // 当前页数
    const [size, setSize] = useState<number>(15);
    // 弹窗
    const [modalState, setModalState] = useState<ModalType>({
        title: "新建用户",
        visible: false
    });

    // 分页数据
    const [meta, setMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });

    // 权限
    const [jurisdictionData, setJurisdictionData] = useState<JurisdictionType[]>([]);

    // 当前数据
    const [currentData, setCurrentData] = useState<DataType | null>(null);

    // 表头
    const columns: ColumnsType<DataType> = [
        {
            title: "姓名",
            dataIndex: "username",
            key: "username",
            align: "center"
        },
        {
            title: "创建时间",
            dataIndex: "created_at",
            key: "created_at",
            align: "center"
        },
        {
            title: "操作",
            dataIndex: "id",
            key: "id",
            align: "center",
            render: (v: string, record: DataType) => {
                return (
                    <div>
                        <Button type="primary" onClick={() => editClick(record)}
                                style={{marginRight: "10px"}}>编辑</Button>
                        <Popconfirm
                            title="删除操作"
                            description={`确定删除${record.username}用户吗？`}
                            onConfirm={() => delClick(v)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="primary" danger>删除</Button>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ]

    // 搜索触发
    const searchFinish = (v: { username: string }) => {
        if (!v.username) {
            setUsername(null);
        } else {
            setUsername(v.username);
        }
    }

    //请求
    const getData = (page: number, username: string | null = null) => {
        setTransition(() => {
            userList(page, size, username).then((r: AxiosResponse) => {
                let {data, meta} = r.data.data;
                data = data.map((v: DataType) => {
                    return {
                        ...v,
                        key: v.id
                    }
                });
                setData(data);
                setMeta(meta);
            }, err => message.error(err))
        })
    }

    // 请求,值没有变化时，不会触发更新，因此需要传入
    useEffect(() => {
        getData(page, username);
    }, [page, username]);

    // 请求权限
    useEffect(() => {
        jurisdictionList().then((r: AxiosResponse) => {
            const {data} = r.data.data;
            setJurisdictionData(data);
        }, err => message.error(err));
    }, [])

    // 新建
    const addClick = () => {
        setModalState({
            visible: true,
            title: "新建用戶"
        });
        setCurrentData(null)
    }

    // 编辑
    const editClick = (v: DataType) => {
        setCurrentData(v);
        const jurisdiction = v.jurisdictions.map(v => v.id);
        userForm.setFieldsValue({...v, jurisdiction});
        setModalState({
            visible: true,
            title: "编辑用户"
        })
    }

    // 用戶表单
    const userFinish = (v: UserBodyType) => {
        let request: Promise<AxiosResponse>;
        if (currentData) {
            request = editUser({username: v.username, jurisdiction: v.jurisdiction}, currentData.id);
        } else {
            request = createUser(v);
        }
        request.then(async (r: AxiosResponse) => {
            userForm.resetFields();
            setModalState(v => {
                return {
                    ...v,
                    visible: false
                }
            });
            getData(page, username);
            await message.success("操作成功");
            if (currentData) {
                window.location.reload();
            }
        }, err => message.error(err));
    }

    // 删除操作
    const delClick = (id: string) => {
        delUser(id).then(async (r: AxiosResponse) => {
            getData(page, username);
            await message.success("删除成功")
        })
    }

    return (
        <div>
            <div className="user-header">
                <Form form={searchForm} name="username" layout="inline" onFinish={searchFinish}>
                    <Form.Item
                        name="username"
                    >
                        <Input placeholder="请输入名字"/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" style={{marginRight: "10px"}} htmlType="submit">
                            搜索
                        </Button>
                        <Button type="primary" htmlType="reset" style={{marginRight: "10px"}}>
                            重置
                        </Button>
                        <Button type="primary" onClick={addClick}>
                            新建
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            {
                loading ? (<RequestLoading/>) : (
                    <Table columns={columns} dataSource={data} pagination={
                        {
                            current: meta.currentPage,
                            defaultCurrent: meta.currentPage,
                            defaultPageSize: meta.perSize,
                            pageSize: meta.perSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            showTotal: (t: number) => `总条数${t}`,
                            total: meta.total,
                            onChange: (page: number, perSize: number) => {
                                setPage(page)
                                setSize(perSize)
                            }
                        }
                    }/>
                )
            }

            <Modal title={modalState.title} open={modalState.visible} footer={null}
                   onCancel={() => {
                       userForm.resetFields();
                       setModalState(v => {
                           return {...v, visible: false}
                       })
                   }}>
                <Form
                    form={userForm}
                    onFinish={userFinish}
                    autoComplete="off"
                >
                    <Form.Item
                        label="名字"
                        name="username"
                        rules={[{required: true, message: '请输入名字'}]}
                    >
                        <Input/>
                    </Form.Item>
                    {
                        !currentData ? <Form.Item
                            label="密码"
                            name="password"
                            rules={[{required: true, message: '请输入密码'}]}
                        >
                            <Input.Password/>
                        </Form.Item> : null
                    }
                    <Form.Item label="权限" name="jurisdiction"
                               className="jurisdiction-box"
                               wrapperCol={{offset: 8, span: 16}}
                               rules={[{required: true, message: '至少选择一项'}]}>
                        <Checkbox.Group style={{width: '100%'}}>
                            <Row>
                                {
                                    jurisdictionData.map(v => {
                                        return (
                                            <Col key={v.id} style={{margin: 0}}>
                                                <Checkbox value={v.id}>{v.name}</Checkbox>
                                            </Col>
                                        )
                                    })
                                }
                            </Row>
                        </Checkbox.Group>
                    </Form.Item>

                    <Form.Item wrapperCol={{offset: 8, span: 16}}>
                        <Button type="primary" htmlType="submit" style={{marginRight: "10px"}}>
                            提交
                        </Button>
                        <Button type="primary" htmlType="reset">
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default User;